package com.example.myapplication.mention

import android.text.Spannable
import android.text.SpannableStringBuilder
import java.util.regex.Pattern

/**
 * Create by Tanzhenxing on 2025/8/30.
 * Description: 智能助手相关@功能
 */

enum class MentionType {
    DEVICE,
    SCENE,
    HOME,
    FIGURE,
    UNKNOW;

    override fun toString(): String {
        return this.name.lowercase()
    }

    companion object {
        fun toMentionType(type: String): MentionType {
            return MentionType.values().find { it.name.equals(type, ignoreCase = false) } ?: UNKNOW
        }
    }
}

/**
 * @的数据模型
 *
 * @param id 唯一标识
 * @param type @的类型
 */
data class SmartAssistantMentionData(
    val id: String,
    val type: MentionType,
    val name: String,
)
private val mentionPattern = Pattern.compile("<at id=\"(.*?)\" type=\"(.*?)\">(.*?)</at>")

fun parseMentionString(input: String?): SpannableStringBuilder? {
    if (input.isNullOrEmpty()) {
        return null
    }
    val matcher = mentionPattern.matcher(input)
    val spannable = SpannableStringBuilder(input)
    // 目前只能@一次，后续如果@多次，需要改为循环处理
    if (matcher.find()) {
        val id = matcher.group(1) // 第1个括号分组 → id
        val type = matcher.group(2) // 第2个括号分组 → type
        val name = matcher.group(3) // 第3个括号分组 → name
        if (!id.isNullOrEmpty() && !type.isNullOrEmpty() && !name.isNullOrEmpty()) {
            val replacement = "@$name"
            spannable.replace(matcher.start(), matcher.end(), replacement)
            // 添加自定义Span
            val span = MentionSpan(
                SmartAssistantMentionData(
                    id = id,
                    type = MentionType.toMentionType(type),
                    name = name
                )
            )
            spannable.setSpan(
                span,
                matcher.start(),
                matcher.start() + replacement.length,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
    }
    return spannable
}

fun packMessageWithMentionSpan(span: CharSequence?): CharSequence? {
    if (span is Spannable) {
        val builder = StringBuilder(span.toString())
        val spans = span.getSpans(0, span.length, MentionSpan::class.java)
        spans.reversed().forEach { item ->
            val data = item.data
            builder.replace(
                span.getSpanStart(item),
                span.getSpanEnd(item),
                "<at id=\"${data.id}\" type=\"${data.type}\">${data.name}</at>"
            )
        }
        return builder.toString()
    }
    return span
}
